﻿using System;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Google.GData.Client;
using Google.GData.YouTube;
using Google.GData.Extensions;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;

namespace YTPD.Lib
{
  public class ResultAggregator
  {
    public const String APPNAME = "youtpd";
    public const String CLIENTID = ""; // CLIENTID is deprecated and no longer needed
    public const String DEVELKEY = "AI39si5dk1T6pVidSYHqXYURvDILR02d5mg_Is6VxcZC948otNsNVbUYOGZc69JAvljxpd5Z8BEbLiEkpv6n2ToExjrZy8hm-w";

    private Feed<Video> _videoFeed = null;

    public ResultAggregator(string playlistUri)
    {
      YouTubeRequestSettings settings = new YouTubeRequestSettings(APPNAME, CLIENTID, DEVELKEY);
      YouTubeRequest request = new YouTubeRequest(settings);

      _videoFeed = request.Get<Video>(new Uri(playlistUri));
    }

    public IList<YoutubeVideo> GetVideos()
    {
      if (_videoFeed == null)
        return new List<YoutubeVideo>();

      var videos = new List<YoutubeVideo>();

      IList<String> szErrorList = new List<String>();
      foreach (Video videoFeedEntry in _videoFeed.Entries)
      {
        try
        {
          var video = new YoutubeVideo
          {
            Title = (videoFeedEntry.Title != null ? videoFeedEntry.Title : "[no title]"),
            Description = (videoFeedEntry.Description != null ? videoFeedEntry.Description : "[no description]"),
            Link = (videoFeedEntry.WatchPage != null ? videoFeedEntry.WatchPage.AbsoluteUri : "http://www.youtube.com/watch?v=" + videoFeedEntry.VideoId)
          };

          var uriConverter = new UriConverter(new WebClientImpl());
          var videoId = uriConverter.GetVideoId(video.Link);
          video.FlvUri = uriConverter.GetFlvUriFromYoutubeVideoUri(videoId);
          if (!string.IsNullOrEmpty(video.FlvUri))
          {
            videos.Add(video);
          }
        }
        catch (NotSignedInException)
        {
          szErrorList.Add(videoFeedEntry.Title);
        }
      }

      if (szErrorList.Count > 0)
        ShowErrors(szErrorList);

      return videos;
    }

    public static void ShowErrors(IList<string> szErrorList)
    {
      String szMessage = "The following videos will not be downloaded (they may be marked private or no longer available):\n\n";
      foreach (string s in szErrorList)
        szMessage += s + "\n";

      System.Windows.Forms.MessageBox.Show(szMessage, "YouTube Playlist Downloader");
    }
  }
}
